import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Card, Button, Space, Row, Col, Typography, ConfigProvider, theme, Select, InputNumber, Input, Slider, ColorPicker, Divider } from 'antd';
import { PlusOutlined, DeleteOutlined, SettingOutlined } from '@ant-design/icons';
import { getOperationTypes, updateSegmentVideoOperations, getSegmentOperations } from '@/services/project';

const { Text } = Typography;
const { Option } = Select;

export interface EffectOperation {
    operation_type: 'animation' | 'background_filling' | 'effect' | 'filter' | 'keyframe' | 'mask' | 'transition';
    params: any;
}

export interface EffectSettings {
    operations: EffectOperation[];
}

interface EffectSettingsProps {
    disabled?: boolean;
    segmentType?: 'video' | 'audio' | 'text';
    // 用于防抖保存的参数
    draftId?: string;
    trackId?: string;
    segmentId?: string;
}

const EffectSettingsComponent: React.FC<EffectSettingsProps> = ({ disabled = false, segmentType = 'video', draftId, trackId, segmentId }) => {
    // 默认的特效设置
    const defaultSettings: EffectSettings = {
        operations: [],
    };

    const [currentSettings, setCurrentSettings] = useState<EffectSettings>(defaultSettings);
    const [operationTypes, setOperationTypes] = useState<Record<string, any>>({});
    const [loading, setLoading] = useState<Record<string, boolean>>({});
    const [loadingOperations, setLoadingOperations] = useState<boolean>(false);

    // 防抖定时器引用
    const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);

    // 初始化时从后端加载数据
    useEffect(() => {
        if (draftId && trackId && segmentId) {
            loadSegmentOperations();
        }
    }, [draftId, trackId, segmentId]);

    // 防抖保存函数
    const debouncedSave = useCallback(
        (data: EffectSettings) => {
            // 清除之前的定时器
            if (debounceTimerRef.current) {
                clearTimeout(debounceTimerRef.current);
            }

            // 设置新的定时器，2秒后执行保存
            debounceTimerRef.current = setTimeout(async () => {
                try {
                    if (draftId && trackId && segmentId) {
                        console.log('保存特效设置到后端:', data);
                        await updateSegmentVideoOperations(draftId, trackId, segmentId, data);
                        console.log('特效设置保存成功');
                    }
                } catch (error) {
                    console.error('保存特效设置失败:', error);
                }
            }, 800);
        },
        [draftId, trackId, segmentId]
    );

    // 组件卸载时清理定时器
    useEffect(() => {
        return () => {
            if (debounceTimerRef.current) {
                clearTimeout(debounceTimerRef.current);
            }
        };
    }, []);

    // 在组件挂载时获取所有操作类型列表
    useEffect(() => {
        const operationTypes = ['animation', 'background_filling', 'effect', 'filter', 'mask', 'transition'];
        operationTypes.forEach((operationType) => {
            fetchOperationTypes(operationType);
        });
    }, []);

    // 加载片段的特效操作
    const loadSegmentOperations = useCallback(async () => {
        if (!draftId || !trackId || !segmentId) {
            return;
        }

        setLoadingOperations(true);
        try {
            const response = await getSegmentOperations(draftId, trackId, segmentId);
            if (response && response.data) {
                const operations = response.data.operations || [];
                const newSettings: EffectSettings = { operations };
                setCurrentSettings(newSettings);
            }
        } catch (error) {
            console.error('加载片段特效操作失败:', error);
        } finally {
            setLoadingOperations(false);
        }
    }, [draftId, trackId, segmentId]);

    // 当 draftId, trackId, segmentId 变化时加载数据
    useEffect(() => {
        if (draftId && trackId && segmentId) {
            loadSegmentOperations();
        }
    }, [draftId, trackId, segmentId, loadSegmentOperations]);

    // 获取操作类型列表
    const fetchOperationTypes = async (operationType: string) => {
        if (operationTypes[operationType] || loading[operationType]) {
            return;
        }

        setLoading((prev) => ({ ...prev, [operationType]: true }));
        try {
            const response = await getOperationTypes(operationType);
            console.log('response', response);
            if (response && response.data) {
                setOperationTypes((prev) => ({
                    ...prev,
                    [operationType]: response.data,
                }));
            }
        } catch (error) {
            console.error(`Failed to fetch operation types for ${operationType}:`, error);
        } finally {
            setLoading((prev) => ({ ...prev, [operationType]: false }));
        }
    };

    const updateSettings = (newSettings: EffectSettings) => {
        setCurrentSettings(newSettings);
        // 触发防抖保存
        debouncedSave(newSettings);
    };

    const addOperation = (operationType: EffectOperation['operation_type']) => {
        const newOperation: EffectOperation = {
            operation_type: operationType,
            params: getDefaultParams(operationType),
        };
        const newSettings = {
            ...currentSettings,
            operations: [...currentSettings.operations, newOperation],
        };
        updateSettings(newSettings);
    };

    const removeOperation = (index: number) => {
        const newOperations = currentSettings.operations.filter((_, i) => i !== index);
        const newSettings = {
            ...currentSettings,
            operations: newOperations,
        };
        updateSettings(newSettings);
    };

    const updateOperation = (index: number, operation: EffectOperation) => {
        const newOperations = [...currentSettings.operations];
        newOperations[index] = operation;
        const newSettings = {
            ...currentSettings,
            operations: newOperations,
        };
        updateSettings(newSettings);
    };

    const getDefaultParams = (operationType: EffectOperation['operation_type']): any => {
        switch (operationType) {
            case 'animation':
                return { animation_type: '渐显', duration: '2s' };
            case 'background_filling':
                return { fill_type: 'blur', blur_amount: 0.0625, color: '#FF0000' };
            case 'effect':
                return { effect_type: '发光', effect_params: [50.0, 100.0] };
            case 'filter':
                return { filter_type: '复古工业', filter_params: { intensity: 80.0 } };
            case 'keyframe':
                return { attribute: 'opacity', time_offset: 2.5, value: 0.8 };
            case 'mask':
                return { mask_type: '圆形', center_x: 50.0, center_y: 50.0, size: 50.0, rotation: 0.0, feather: 0.0, invert: false };
            case 'transition':
                return { transition_type: '叠化', duration: '1s' };
            default:
                return {};
        }
    };

    const renderAnimationParams = (params: any, index: number) => {
        const operationType = 'animation';
        const operationData = operationTypes[operationType];
        // animation 类型有复杂的嵌套结构，需要根据片段类型选择
        const operationInfo = operationData?.operation_info;
        let types: string[] = [];

        if (operationInfo) {
            // 根据片段类型选择对应的动画类型
            if (segmentType === 'text') {
                // 文本片段：合并所有文本动画类型
                types = [...(operationInfo.intro?.text_types || []), ...(operationInfo.outro?.text_types || []), ...(operationInfo.loop?.text_types || [])];
            } else {
                // 视频片段：合并所有视频动画类型
                types = [...(operationInfo.intro?.video_types || []), ...(operationInfo.outro?.video_types || [])];
            }
        }

        return (
            <Row gutter={8}>
                <Col span={12}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>动画类型</Text>
                    <Select
                        value={params.animation_type}
                        onChange={(value) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.animation_type = value;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        style={{ width: '100%' }}
                        size="small"
                        loading={loading[operationType]}
                    >
                        {types.map((type: string) => (
                            <Option key={type} value={type}>
                                {type}
                            </Option>
                        ))}
                    </Select>
                </Col>
                <Col span={12}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>持续时间</Text>
                    <Input
                        value={params.duration}
                        onChange={(e) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.duration = e.target.value;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        size="small"
                        placeholder="2s"
                    />
                </Col>
            </Row>
        );
    };

    const renderBackgroundFillingParams = (params: any, index: number) => {
        const operationType = 'background_filling';
        const operationData = operationTypes[operationType];
        const types = operationData?.operation_info?.types || [];

        return (
            <Row gutter={8}>
                <Col span={8}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>填充类型</Text>
                    <Select
                        value={params.fill_type}
                        onChange={(value) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.fill_type = value;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        style={{ width: '100%' }}
                        size="small"
                        loading={loading[operationType]}
                    >
                        {types.map((type: string) => (
                            <Option key={type} value={type}>
                                {type}
                            </Option>
                        ))}
                    </Select>
                </Col>
                <Col span={8}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>模糊程度</Text>
                    <Slider
                        min={0}
                        max={1}
                        step={0.01}
                        value={params.blur_amount}
                        onChange={(value) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.blur_amount = value;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                    />
                </Col>
                <Col span={8}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>颜色</Text>
                    <ColorPicker
                        value={params.color}
                        onChange={(color) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.color = color.toHexString();
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        size="small"
                        style={{ width: '100%' }}
                    />
                </Col>
            </Row>
        );
    };

    const renderEffectParams = (params: any, index: number) => {
        const operationType = 'effect';
        const operationData = operationTypes[operationType];
        const types = operationData?.operation_info?.types || [];

        return (
            <Row gutter={8}>
                <Col span={12}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>特效类型</Text>
                    <Select
                        value={params.effect_type}
                        onChange={(value) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.effect_type = value;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        style={{ width: '100%' }}
                        size="small"
                        loading={loading[operationType]}
                    >
                        {types.map((type: string) => (
                            <Option key={type} value={type}>
                                {type}
                            </Option>
                        ))}
                    </Select>
                </Col>
                <Col span={12}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>参数</Text>
                    <Input
                        value={params.effect_params.join(', ')}
                        onChange={(e) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.effect_params = e.target.value
                                .split(',')
                                .map((v) => parseFloat(v.trim()))
                                .filter((v) => !isNaN(v));
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        size="small"
                        placeholder="50.0, 100.0"
                    />
                </Col>
            </Row>
        );
    };

    const renderFilterParams = (params: any, index: number) => {
        const operationType = 'filter';
        const operationData = operationTypes[operationType];
        const types = operationData?.operation_info?.types || [];

        return (
            <Row gutter={8}>
                <Col span={12}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>滤镜类型</Text>
                    <Select
                        value={params.filter_type}
                        onChange={(value) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.filter_type = value;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        style={{ width: '100%' }}
                        size="small"
                        loading={loading[operationType]}
                    >
                        {types.map((type: string) => (
                            <Option key={type} value={type}>
                                {type}
                            </Option>
                        ))}
                    </Select>
                </Col>
                <Col span={12}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>强度</Text>
                    <Slider
                        min={0}
                        max={100}
                        value={params.filter_params.intensity}
                        onChange={(value) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.filter_params.intensity = value;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                    />
                </Col>
            </Row>
        );
    };

    const renderKeyframeParams = (params: any, index: number) => (
        <Row gutter={8}>
            <Col span={8}>
                <Text style={{ color: '#ffffff', fontSize: '11px' }}>属性</Text>
                <Select
                    value={params.attribute}
                    onChange={(value) => {
                        const newOperation = { ...currentSettings.operations[index] };
                        newOperation.params.attribute = value;
                        updateOperation(index, newOperation);
                    }}
                    disabled={disabled}
                    style={{ width: '100%' }}
                    size="small"
                >
                    <Option value="opacity">透明度</Option>
                    <Option value="scale">缩放</Option>
                    <Option value="rotation">旋转</Option>
                </Select>
            </Col>
            <Col span={8}>
                <Text style={{ color: '#ffffff', fontSize: '11px' }}>时间偏移</Text>
                <InputNumber
                    min={0}
                    step={0.1}
                    value={params.time_offset}
                    onChange={(value) => {
                        const newOperation = { ...currentSettings.operations[index] };
                        newOperation.params.time_offset = value || 0;
                        updateOperation(index, newOperation);
                    }}
                    disabled={disabled}
                    style={{ width: '100%' }}
                    size="small"
                />
            </Col>
            <Col span={8}>
                <Text style={{ color: '#ffffff', fontSize: '11px' }}>值</Text>
                <InputNumber
                    min={0}
                    max={1}
                    step={0.1}
                    value={params.value}
                    onChange={(value) => {
                        const newOperation = { ...currentSettings.operations[index] };
                        newOperation.params.value = value || 0;
                        updateOperation(index, newOperation);
                    }}
                    disabled={disabled}
                    style={{ width: '100%' }}
                    size="small"
                />
            </Col>
        </Row>
    );

    const renderMaskParams = (params: any, index: number) => {
        const operationType = 'mask';
        const operationData = operationTypes[operationType];
        const types = operationData?.operation_info?.types || [];

        return (
            <Row gutter={8}>
                <Col span={6}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>蒙版类型</Text>
                    <Select
                        value={params.mask_type}
                        onChange={(value) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.mask_type = value;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        style={{ width: '100%' }}
                        size="small"
                        loading={loading[operationType]}
                    >
                        {types.map((type: string) => (
                            <Option key={type} value={type}>
                                {type}
                            </Option>
                        ))}
                    </Select>
                </Col>
                <Col span={6}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>中心X</Text>
                    <InputNumber
                        min={0}
                        max={100}
                        value={params.center_x}
                        onChange={(value) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.center_x = value || 0;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        style={{ width: '100%' }}
                        size="small"
                    />
                </Col>
                <Col span={6}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>中心Y</Text>
                    <InputNumber
                        min={0}
                        max={100}
                        value={params.center_y}
                        onChange={(value) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.center_y = value || 0;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        style={{ width: '100%' }}
                        size="small"
                    />
                </Col>
                <Col span={6}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>大小</Text>
                    <InputNumber
                        min={0}
                        max={100}
                        value={params.size}
                        onChange={(value) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.size = value || 0;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        style={{ width: '100%' }}
                        size="small"
                    />
                </Col>
            </Row>
        );
    };

    const renderTransitionParams = (params: any, index: number) => {
        const operationType = 'transition';
        const operationData = operationTypes[operationType];
        const types = operationData?.operation_info?.types || [];

        return (
            <Row gutter={8}>
                <Col span={12}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>转场类型</Text>
                    <Select
                        value={params.transition_type}
                        onChange={(value) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.transition_type = value;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        style={{ width: '100%' }}
                        size="small"
                        loading={loading[operationType]}
                    >
                        {types.map((type: string) => (
                            <Option key={type} value={type}>
                                {type}
                            </Option>
                        ))}
                    </Select>
                </Col>
                <Col span={12}>
                    <Text style={{ color: '#ffffff', fontSize: '11px' }}>持续时间</Text>
                    <Input
                        value={params.duration}
                        onChange={(e) => {
                            const newOperation = { ...currentSettings.operations[index] };
                            newOperation.params.duration = e.target.value;
                            updateOperation(index, newOperation);
                        }}
                        disabled={disabled}
                        size="small"
                        placeholder="1s"
                    />
                </Col>
            </Row>
        );
    };

    const renderOperationParams = (operation: EffectOperation, index: number) => {
        switch (operation.operation_type) {
            case 'animation':
                return renderAnimationParams(operation.params, index);
            case 'background_filling':
                return renderBackgroundFillingParams(operation.params, index);
            case 'effect':
                return renderEffectParams(operation.params, index);
            case 'filter':
                return renderFilterParams(operation.params, index);
            case 'keyframe':
                return renderKeyframeParams(operation.params, index);
            case 'mask':
                return renderMaskParams(operation.params, index);
            case 'transition':
                return renderTransitionParams(operation.params, index);
            default:
                return null;
        }
    };

    const getOperationTypeName = (type: EffectOperation['operation_type']): string => {
        const typeNames = {
            animation: '动画',
            background_filling: '背景填充',
            effect: '特效',
            filter: '滤镜',
            keyframe: '关键帧',
            mask: '蒙版',
            transition: '转场',
        };
        return typeNames[type] || type;
    };

    const darkTheme = {
        algorithm: theme.darkAlgorithm,
        token: {
            colorPrimary: '#715bb8',
            colorBgContainer: '#2a2a2a',
            colorBgElevated: '#2a2a2a',
            colorText: '#ffffff',
            colorTextSecondary: 'rgba(255, 255, 255, 0.7)',
            colorBorder: '#434343',
            colorBorderSecondary: '#434343',
            borderRadius: 6,
            colorFillSecondary: '#434343',
        },
        components: {
            Card: {
                colorBgContainer: '#2a2a2a',
                colorBorder: '#434343',
            },
            Select: {
                colorBgContainer: '#2a2a2a',
                colorBorder: '#434343',
                colorText: '#ffffff',
            },
            Input: {
                colorBgContainer: '#2a2a2a',
                colorBorder: '#434343',
                colorText: '#ffffff',
            },
            InputNumber: {
                colorBgContainer: '#2a2a2a',
                colorBorder: '#434343',
                colorText: '#ffffff',
            },
            Slider: {
                colorBgContainer: '#2a2a2a',
                colorPrimary: '#715bb8',
                colorPrimaryBorder: '#715bb8',
                colorFillSecondary: '#434343',
                colorText: '#ffffff',
            },
            ColorPicker: {
                colorBgContainer: '#2a2a2a',
                colorBorder: '#434343',
            },
            Button: {
                colorBgContainer: '#2a2a2a',
                colorBorder: '#434343',
                colorText: '#ffffff',
            },
        },
    };

    return (
        <ConfigProvider theme={darkTheme}>
            <Card
                title={
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <SettingOutlined style={{ color: '#715bb8' }} />
                        <span style={{ color: '#ffffff' }}>特效设置</span>
                    </div>
                }
                style={{
                    backgroundColor: '#2a2a2a',
                    border: '1px solid #434343',
                    borderRadius: '8px',
                }}
                styles={{ body: { padding: '12px' } }}
            >
                {loadingOperations ? (
                    <div style={{ textAlign: 'center', padding: '20px', color: '#ffffff' }}>加载特效设置中...</div>
                ) : (
                    <Space direction="vertical" size="small" style={{ width: '100%' }}>
                        {currentSettings.operations.map((operation, index) => (
                            <div key={index} style={{ marginBottom: '8px', padding: '8px', backgroundColor: '#1a1a1a', borderRadius: '4px' }}>
                                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
                                    <Text style={{ color: '#ffffff', fontSize: '12px', fontWeight: 'bold' }}>{getOperationTypeName(operation.operation_type)}</Text>
                                    <Button size="small" danger icon={<DeleteOutlined />} onClick={() => removeOperation(index)} disabled={disabled} />
                                </div>
                                {renderOperationParams(operation, index)}
                            </div>
                        ))}

                        <Divider style={{ backgroundColor: '#434343', margin: '6px 0' }} />

                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                            <Button size="small" icon={<PlusOutlined />} onClick={() => addOperation('animation')} disabled={disabled}>
                                添加动画
                            </Button>
                            <Button size="small" icon={<PlusOutlined />} onClick={() => addOperation('background_filling')} disabled={disabled}>
                                添加背景填充
                            </Button>
                            <Button size="small" icon={<PlusOutlined />} onClick={() => addOperation('effect')} disabled={disabled}>
                                添加特效
                            </Button>
                            <Button size="small" icon={<PlusOutlined />} onClick={() => addOperation('filter')} disabled={disabled}>
                                添加滤镜
                            </Button>
                            <Button size="small" icon={<PlusOutlined />} onClick={() => addOperation('keyframe')} disabled={disabled}>
                                添加关键帧
                            </Button>
                            <Button size="small" icon={<PlusOutlined />} onClick={() => addOperation('mask')} disabled={disabled}>
                                添加蒙版
                            </Button>
                            <Button size="small" icon={<PlusOutlined />} onClick={() => addOperation('transition')} disabled={disabled}>
                                添加转场
                            </Button>
                        </div>
                    </Space>
                )}
            </Card>
        </ConfigProvider>
    );
};

export default EffectSettingsComponent;
